import { execSync } from "node:child_process";
import { IUserTask } from "./usertask";
import fs from "node:fs";
import inquirer from "inquirer";
import { colorize } from "./colortext";


function writeTempScript(content: string): string {
    let tempPath = fs.mkdtempSync("tempScript_") + ".sh";
    fs.writeFileSync(tempPath, content);
    return tempPath;
}

export function executeScript(script: string): void {
    let tempPath = writeTempScript(script);
    // console.log("Executing script:");
    // console.log(script);
    execSync(`bash ${tempPath}`, { stdio: "inherit" });
    fs.unlinkSync(tempPath);
}

export async function executeTask(task: IUserTask): Promise<void> {
    if (task.type === "cmd") {
        console.log(colorize("Executing command:", "white", "black", "bright"), task.content);
    } else if (task.type === "script") {
        console.log(colorize("Executing script:", "white", null, "bright"));
        console.log(colorize(task.content, "white", null, "bright"));
    }

    if (task.confirmationRequired) {
        console.log(colorize(task.description, "green", null, null));
        let answers = await inquirer.prompt([
            {
            type: 'confirm',
            name: 'confirm',
            message: 'Do you want to continue?',
            default: false
            }
        ]);

        if (!answers.confirm) {
            console.log("Task cancelled.");
            return;
        }
    }

    try {
        if (task.type === "cmd") {
            execSync(task.content, { stdio: "inherit" });
        } else if (task.type === "script") {
            executeScript(task.content);
        } else {
            console.error("Unknown task type:", task.type);
        }
    } catch (error) {
        console.error(colorize("Error executing task:", "white", "red", null), (error as any).message || "Unknown error");
    }
}